package com.demo.webapp.servlet;

import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.demo.core.model.File;
import com.demo.core.service.DocumentService;

/**
 * DB文件下载Servlet
 * 依赖于Spring容器和CORE包
 * @author ryuu.kk
 *
 */
public class DBFileDownloadServlet extends DownloadServlet {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -7955042153801484409L;
	
	/**
	 * Spring容器上下文
	 */
	protected ApplicationContext applicationContext;
	
	/**
	 * 文档管理服务
	 */
	private static String DOCUMENT_BEAN_NAME = "documentService";
	
	/**
	 * 文档服务
	 */
	private DocumentService documentService;
	
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		//取得spring上下文
		applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	}

	@Override
	protected InputStream getFileInputStream(FileInfo fileInfo) throws ServletException {

		return documentService.queryFileStream(fileInfo.getFileId());
	}
	
	@Override
	protected FileInfo getFileInfo(HttpServletRequest request) throws FileNotFoundException {
		
		String id = request.getParameter("id");
		Long fileId = null;
		String fileName = null;
		String contentType = null;
		String uuid = null;
		String path= null;
		long size = 0;
		if (StringUtils.isNotBlank(id)) {
			fileId = Long.parseLong(id);
		}
		
		if (documentService == null) {
			documentService = applicationContext.getBean(DOCUMENT_BEAN_NAME, DocumentService.class);
		}
		
		//id为空或文件不存在,则抛出异常
		if (StringUtils.isBlank(id) || !documentService.fileExists(fileId)) {
			throw new FileNotFoundException("file ID:" + fileId + " not found.");
		}
		
		//取得文件对象,但不取得文件内容
		File file = documentService.findFile(fileId, false);
		
		if (file.isEnabled()) {
			//文件不可用
		}
		
		fileName = file.getName();
		contentType = file.getContentType();
		size = file.getSize();
		uuid = file.getUuid();
		path = file.getPath();
		//FileNotFoundException
		return new FileInfo(fileId, uuid, fileName, path, contentType, (int)size);
	}
}
